from django.shortcuts import render
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django_filters import rest_framework as filters
from .models import Order, OrderItem, Review
from .serializers import OrderSerializer, OrderItemSerializer, ReviewSerializer
from restaurant.models import Restaurant, Dish

class OrderFilter(filters.FilterSet):
    start_date = filters.DateFilter(field_name='created_at', lookup_expr='gte')
    end_date = filters.DateFilter(field_name='created_at', lookup_expr='lte')
    
    class Meta:
        model = Order
        fields = ['status', 'start_date', 'end_date']

class OrderViewSet(viewsets.ModelViewSet):
    serializer_class = OrderSerializer
    permission_classes = [IsAuthenticated]
    filter_class = OrderFilter
    
    def get_queryset(self):
        user = self.request.user
        if user.is_staff:
            return Order.objects.all()
        # 普通用户只能看到自己的订单，餐厅店主可以看到自己餐厅的订单
        restaurant_orders = Order.objects.filter(restaurant__owner=user)
        user_orders = Order.objects.filter(user=user)
        return (restaurant_orders | user_orders).distinct()
    
    def perform_create(self, serializer):
        items_data = self.request.data.get('items', [])
        restaurant_id = self.request.data.get('restaurant')
        restaurant = Restaurant.objects.get(id=restaurant_id)
        
        # 验证所有菜品是否属于同一餐厅
        for item in items_data:
            dish = Dish.objects.get(id=item['dish'])
            if dish.restaurant.id != restaurant.id:
                raise serializers.ValidationError("所有菜品必须来自同一餐厅")
        
        serializer.save(
            user=self.request.user,
            context={'items': items_data}
        )
    
    @action(detail=True, methods=['post'])
    def add_review(self, request, pk=None):
        order = self.get_object()
        if order.user != request.user:
            return Response(
                {"error": "只能评价自己的订单"},
                status=status.HTTP_403_FORBIDDEN
            )
        if order.status != 'completed':
            return Response(
                {"error": "只能评价已完成的订单"},
                status=status.HTTP_400_BAD_REQUEST
            )
        if hasattr(order, 'review'):
            return Response(
                {"error": "该订单已经评价过了"},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        serializer = ReviewSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save(order=order)
            # 更新餐厅评分
            restaurant = order.restaurant
            reviews = Review.objects.filter(order__restaurant=restaurant)
            if reviews.exists():
                avg_rating = reviews.aggregate(Avg('rating'))['rating__avg']
                restaurant.rating = avg_rating
                restaurant.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    
    @action(detail=True, methods=['post'])
    def update_status(self, request, pk=None):
        order = self.get_object()
        new_status = request.data.get('status')
        
        # 验证状态转换的合法性
        if not self._is_valid_status_transition(order.status, new_status):
            return Response(
                {"error": "非法的状态转换"},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        # 验证权限
        if not self._has_permission_for_status_update(request.user, order, new_status):
            return Response(
                {"error": "没有权限执行此操作"},
                status=status.HTTP_403_FORBIDDEN
            )
        
        order.status = new_status
        order.save()
        return Response(OrderSerializer(order).data)
    
    def _is_valid_status_transition(self, current_status, new_status):
        valid_transitions = {
            'pending': ['paid', 'cancelled'],
            'paid': ['preparing', 'cancelled'],
            'preparing': ['delivering'],
            'delivering': ['completed'],
            'completed': [],
            'cancelled': []
        }
        return new_status in valid_transitions.get(current_status, [])
    
    def _has_permission_for_status_update(self, user, order, new_status):
        if user.is_staff:
            return True
        
        if user == order.user:
            # 用户可以取消未开始准备的订单
            return new_status == 'cancelled' and order.status in ['pending', 'paid']
        
        if user == order.restaurant.owner:
            # 餐厅店主可以更新订单状态（除了支付和取消）
            return new_status not in ['paid', 'cancelled']
        
        return False
